/**
 * Testing harness for testing the tango PKI implementation
 */
module PKITest;

import tango.stdc.signal;
import tango.io.Stdout;
import tango.io.device.File;
import tango.io.stream.TextFile;
import tango.io.stream.Format;
import tango.time.Time;

import tango.net.util.PKI;

static const uint KEY_BIT_LEN = 2048;
static const string PASS = "ExamplePassword";
static const string PRIV_FILE = "private.pem";

void main() {
	PrivateKey priv;
	PublicKey pub;
    string pt1, et1, dt1;
    
    priv = getKeys("Password");
    pub = priv.publicKey();
    
    pt1 = "Test string for using PKI encryption.";
    
    Stdout.formatln("Plaintext:\t{}", pt1);
    et1 = cast(string)pub.encrypt(cast(ubyte[])pt1);
    Stdout.formatln("Ciphertext:\t{}", et1);
    dt1 = cast(string)priv.decrypt(cast(ubyte[])et1);
    Stdout.formatln("Decodetext:\t{}", dt1);

}

PrivateKey getKeys(string pass, string privF = PRIV_FILE){
	TextFileInput prv;
	PrivateKey priv = null;
    
    try {
    	prv = new TextFileInput(privF, File.ReadExisting);
    	
    	Stdout.formatln("Using existing file for PKI:\t{}\n", privF);
    	
    	auto pem = cast(char[])prv.load;
    	prv.close;
    	
    	priv = new PrivateKey(pem, pass);
    }catch(Exception e) {
    	Stdout.formatln("{}", e.msg);
    	priv = null;
    }
    
    if(priv is null){
    	auto prf = new File(privF, File.ReadWriteCreate);
    	
    	Stdout.formatln("Creating new PKI and storing in:\t{}\n", privF);
    	
    	priv = new PrivateKey(KEY_BIT_LEN);
    	prf.write(priv.pemFormat(pass));
    	
    	prf.close;
    }
    
    return priv;
}